const db = require("../models");
const DAO = require("../dao/DAO");
const logger = require("../utils/utils.logger");
const model = db.village;

// 创建用户
exports.create = async (req, res, next) => {
	try {
		const pm = req.body;
		if (!pm.villageName) return res.sendResultAto(null, 605, '乡村不能为空')
		const params = { villageName: pm.villageName }

		// 判断是否存在
		const exist = await model.findOne({
			where: params
		});
		if (exist) {
			return res.sendResultAto(null, 500, '乡村已存在')
		}
		// 新增
		await model.create(params)
		res.sendResultAto(null, 200, '添加成功！')
	} catch (error) {
		logger.error(error)
		next('服务器内部错误')
	}
};

// 查询用户
exports.findAll = async (req, res, next) => {
	try {
		const list = await DAO.list(model, {
			sort: {
				prop: 'villageId',
				order: 'desc',
			}
		})
		res.sendResult(list)
	} catch (error) {
		logger.error(error)
		next('服务器内部错误')
	}
};

// 更新用户
exports.update = async (req, res, next) => {
	try {
		const { villageId, villageName } = req.body;
		const data = await model.update({ villageName }, {
			where: {
				villageId
			}
		});
		if (data[0]) {
			res.sendResultAto(null, 200, '修改成功！')
		} else {
			res.sendResultAto(null, 500, '数据不存在')
		}
	} catch (error) {
		logger.error(error)
		next('服务器内部错误')
	}
};

// 删除用户
exports.delete = async (req, res, next) => {
	try {
		const villageId = req.params.id;
		// 请求验证
		if (!villageId) return res.sendResult({ data: '', code: 605, message: "ID不能为空！" })
		const data = await model.destroy({ where: { villageId } })
		if (data) {
			res.sendResultAto(null, 200, '删除成功！')
		} else {
			res.sendResultAto(null, 500, '数据不存在')
		}
	} catch (error) {
		logger.error(error)
		next('服务器内部错误')
	}
};




